<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>弹出球</title>
    <style>
      #dv {
        position: absolute;
        width: 800px;
        height: 600px;
        background: #ccc;
        top: 100px;
        left: 100px;
      }
    </style>
  </head>
  <body>
    <input type="button" value="弹出球" id="btn" />

    <div id="dv"></div>
    <script>
      var dv = document.getElementById('dv');

      var color=['red','white','yellow','pink','green','orange'];

      document.getElementById("btn").onclick = function () {
        // 创建球的div
        var ball = document.createElement("div");
        ball.style.cssText = "position:absolute;border-radius:50%;";
        // 球宽高随机
        var wh=Math.floor(Math.random()*50)+30;
        ball.style.width = wh+"px";
        ball.style.height = wh+"px";
        // ball.style.backgroundColor ="red";
        // 随机颜色
        ball.style.backgroundColor = color[Math.round(Math.random()*color.length)];

        dv.appendChild(ball); // 向div中添加创建名为ball的div

        // 球在屏幕中间1
        var top = dv.clientHeight / 2 - ball.offsetHeight / 2;
        var lef = dv.clientWidth / 2 - ball.offsetWidth / 2;

        // // 获取宽高
        // console.log(dv.clientWidth);
        // console.log(dv.clientHeight);
        // console.log(ball.offsetWidth);
        // console.log(ball.offsetHeight);

        // 球在屏幕中间2
        ball.style.top = top + "px";
        ball.style.left = lef + "px";

        var x = Math.floor(Math.random()*10)+1;
        var y = Math.floor(Math.random()*10)+1;
        setInterval(function () {
          lef += x;
          top += y;

          if (lef < 0 || lef > dv.offsetWidth - ball.offsetWidth) {
            x = -x;
          }
          if (top < 0 || top > dv.offsetHeight - ball.offsetHeight) {
            y = -y;
          }
          ball.style.top = top + "px";
          ball.style.left = lef + "px";
        }, 20);
      };
    </script>
  </body>
</html>
